package com.lzp.jdbc;

import java.sql.*;

public class JDBCDemo {

    Connection conn = null;
    Statement stmt = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    public static void main(String[] args) {
        JDBCDemo jdbcDemo = new JDBCDemo();
        jdbcDemo.testPrepareStatement();
    }

    /**
     * 测试使用Statement查询
     */
    public void testStatement() {
        try {
            String sql = "select * from user";
            conn = JDBCUtil.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                System.out.println(rs.getInt("id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(rs, stmt, conn);
        }
    }

    /**
     * 测试更新
     */
    public void testUpdate() {
        String sql = "update user set username = 'jdbc' where id = 63";
        try {
            conn = JDBCUtil.getConnection();
            stmt = conn.createStatement();
            int result = stmt.executeUpdate(sql);
            assert result == 1;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(stmt, conn);
        }
    }

    /**
     * 测试使用PrepareStatement查询
     */
    public void testPrepareStatement() {
        try {
            conn = JDBCUtil.getConnection();
            String sql = "select * from user where id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, 63);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getString("username"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
